package com.kehutong.charge.service.impl;

import com.kehutong.charge.dao.ChargeMeterDao;
import com.kehutong.charge.dto.MeterManageImportDTO;
import com.kehutong.charge.dto.MeterStatistDTO;
import com.kehutong.charge.entity.ChargeHouseConfig;
import com.kehutong.charge.entity.MeterClassify;
import com.kehutong.charge.entity.MeterManage;
import com.kehutong.charge.entity.MeterTypeConfig;
import com.kehutong.charge.service.CommonService;
import com.kehutong.charge.service.MeterManageService;
import com.kehutong.charge.util.CommonClient;
import com.kehutong.charge.util.ConvertUtil;
import com.kehutong.charge.util.enums.ChargeLogEnum;
import com.kehutong.charge.util.enums.ChargeStatusEnum;
import com.kehutong.charge.vo.MeterManageTemplateExcelVO;
import com.kehutong.common.DeptService;
import com.kehutong.common.dto.DeptDTO;
import com.kehutong.common.errcode.Assert;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.excel.entity.ImportResult;
import com.kehutong.common.excel.tool.ExcelTool;
import com.kehutong.common.util.ConvertUtils;
import com.kehutong.common.util.ListUtils;
import com.kehutong.common.util.Token;
import org.coraframework.bean.Beans;
import org.coraframework.converter.util.StringUtil;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.Condition;
import org.coraframework.orm.jdbc.execute.PageCondition;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: kht
 * @description: MeterManageServiceImpl
 * @author: joneron
 * @create: 2021/6/21
 **/
public class MeterManageServiceImpl implements MeterManageService {

    private static final Logger logger = LoggerFactory.getLogger(MeterManageServiceImpl.class);



    @Inject
    DeptService deptService;
    @Inject
    private JdbcSession jdbcSession;
    @Inject
    CommonClient commonClient;
    @Inject
    ChargeMeterDao chargeMeterDao;
    @Inject
    ExcelTool excelTool;

    @Inject
    CommonService commonService;



    @Override
    public void pageExport(HttpServletRequest req, HttpServletResponse resp, JSONObject jsonObject) {
        jsonObject.put("pageNo", 1);
        jsonObject.put("pageSize", ExcelTool.MAX_ROWS);
        List<MeterManage> list = findPage(jsonObject).getList();
        Assert.notEmpty(list,"在此小区未找到相关的仪表数据.");
        List<MeterManageTemplateExcelVO> manageDTOList = ListUtils.copyBeanList(list, MeterManageTemplateExcelVO::new);

        List<Map<String,Object>> houseList = null;
        try {
            Set<String> ids = manageDTOList.stream().map(l -> l.getHouseNo()).collect(Collectors.toSet());
            JSONObject param = new JSONObject();
            param.put("ids",ids);
            houseList = commonClient.getHouseByIds(param);
        } catch (Exception e) {
            logger.error("小区仪表导出时获取房屋信息错误",e);
            excelTool.excelDownload(req,resp,manageDTOList,"所属小区仪表导出");
        }
        List<Map<String, Object>> finalHouseList = houseList;
        manageDTOList.stream().map(r-> finalHouseList.stream().filter(h->h.get("id").equals(r.getHouseNo())).findFirst().map(h->{
            r.setCommunityName(ConvertUtils.toNoNullString(h.get("communityName")));
            r.setBuildName(ConvertUtils.toNoNullString(h.get("buildName")));
            r.setUnitName(ConvertUtils.toNoNullString(h.get("unitName")));
            r.setFloorName(ConvertUtils.toNoNullString(h.get("floorName")));
            r.setHouseName(ConvertUtils.toNoNullString(h.get("houseName")));
            return r;
        }).orElse(null)).filter(java.util.Objects::nonNull).collect(Collectors.toList());

        excelTool.excelDownload(req,resp,manageDTOList,"所属小区仪表导出");
    }


    @Override
    public Page<MeterManage> findPage(JSONObject jsonObject) {
        FindPage<MeterManage> find = jdbcSession.findPage(MeterManage.class);
        find.eq("deleted", false);
        find.like(jsonObject,"meterNum");
        find.like(jsonObject,"meterNo");
        find.eq(jsonObject,"communityNo");
        find.eq(jsonObject,"meterClassifyNo");
        find.eq(jsonObject,"meterTypeNo");
        find.like(jsonObject,"meterAddress");
        //添加选中导出条件
        JSONArray exportIdList = jsonObject.getJSONArray("exportIdList");
        if(!Objects.isEmpty(exportIdList)){
            find.in("meterNo",exportIdList);
        }
        find.like(jsonObject,"meterAddress");
        find.order("sort", "desc");
        find.order("createTime", "desc");

        find.page(jsonObject);

        return find.exe();
    }


    @Override
    public List<MeterManage> findList(JSONObject jsonObject) {
        return jdbcSession.findArray(MeterManage.class)
                .eq("deleted", false)
                .eq(jsonObject, "meterTypeNo")
                .eq(jsonObject, "meterClassifyNo")
                .exe();
    }


    @Override
    public Object save(MeterManage meterManage) {
        return null;
    }


    @Override
    public Object save(MeterManage entity, Token token) throws Exception {
        entity.setCreateName(token.getUsername());
        List<String> departList = token.getDepartments();
        if(null != departList && departList.size() > 0){
            logger.error("用户{}数据异常，部门为空！",token.getUsername());
            DeptDTO deptDTO = deptService.getDept(departList.get(0));
            entity.setDepartmentNo(deptDTO.getDepartmentNo());
            entity.setDepartmentNos(deptDTO.getDepartmentNos());
            entity.setDepartmentName(deptDTO.getDepartmentName());
        }
        String name = entity.getMeterNo();
        List<MeterManage> listMt = jdbcSession.findArray(MeterManage.class)
                .eq("deleted", false)
                .eq("meterNo",name)
                .exe();
        if(!listMt.isEmpty() && listMt.size() > 0){
            return Result.error(2021, "仪表编号不能重复！");
        }

        listMt = jdbcSession.findArray(MeterManage.class)
                .eq("deleted", false)
                .eq("meterClassifyNo",entity.getMeterClassifyNo())
                .eq("meterTypeNo", entity.getMeterTypeNo())
                .eq("houseNo", entity.getHouseNo())
                .exe();

        if(!listMt.isEmpty() && listMt.size() > 0){
            return Result.error(2022, "该房屋地址已创建仪表分类！");
        }

        MeterClassify classify = jdbcSession.findOne(MeterClassify.class)
                .eq("deleted", false)
                .eq("id", entity.getMeterClassifyNo())
                .exe();
        if(null != classify && !classify.isStatus()){
            return Result.error(2022, "此仪表分类已被禁用，请到仪表类型中开启再添加！");
        }

        commonService.insetLogger(name,
                ChargeLogEnum.LOG_CHARGE_METER.getDesc(),
                "添加仪表",
                ChargeStatusEnum.CS_SUCCESS.getDesc(),
                ChargeStatusEnum.CS_SUCCESS.getDesc(), "操作成功", token.getUsername());

        MeterTypeConfig meterTypeConfig = jdbcSession.findOne(MeterTypeConfig.class).eq("deleted", false).eq("id", entity.getMeterTypeNo()).exe();
        entity.setMeterTypeName(meterTypeConfig.getTypeName());
        return jdbcSession.insert(entity);
    }

    @Override
    public void templateExport(HttpServletRequest req, HttpServletResponse resp,Token token) throws Exception {
        //远程获取所有房屋
        List<ChargeHouseConfig> allHouseList = commonClient.getResidentHouseList(token);
        if(Objects.isEmpty(allHouseList)){
            logger.error("[水电燃气仪表模板下载]获取全部小区失败，启用备份模板");
            List<MeterManageTemplateExcelVO> template = new ArrayList<>();
            MeterManageTemplateExcelVO vo = new MeterManageTemplateExcelVO();
            vo.setMeterNo("DB20216010110（示例）");
            vo.setMeterTypeName("燃气表");
            vo.setMeterClassifyName("业主仪表");
            vo.setCommunityName("七星小区");
            vo.setBuildName("1栋");
            vo.setUnitName("1单元");
            vo.setFloorName("1");
            vo.setHouseName("001");
            template.add(vo);
            excelTool.excelDownload(req, resp, template, "水电燃气仪表导入模板");
            return;
        }
        List<MeterManageTemplateExcelVO> template = ListUtils.copyList(allHouseList, MeterManageTemplateExcelVO::new);
        MeterManageTemplateExcelVO vo = template.get(0);
        vo.setMeterNo("DB20216010110（示例）");
        vo.setMeterTypeName("燃气表");
        vo.setMeterClassifyName("业主仪表");
        excelTool.excelDownload(req, resp, template, "水电燃气仪表导入模板");
    }

    @Override
    public Object switchStatus(String id) {
        logger.info("切换仪表管理状态id=" + id);
        MeterManage meterManage = jdbcSession.findOne(MeterManage.class).eq("id", id).exe();
        if (meterManage == null) {
            return 0;
        }

        // 判断是否已有同类启用
        if (!meterManage.isStatus()) {
            List<MeterManage> meterManageList = jdbcSession.findArray(MeterManage.class).eq("communityNo", meterManage.getCommunityNo())
                    .eq("houseNo", meterManage.getHouseNo()).eq("meterTypeNo", meterManage.getMeterTypeNo())
                    .eq("status", true).eq("deleted", false).noEq("id", id).exe();
            if (Objects.nonEmpty(meterManageList)) {
                logger.info("已有同类型启用");
                return Result.error(3002, "同一仪表类型只能有一个启用状态");
            }
        }

        meterManage.setStatus(!meterManage.isStatus());
        return jdbcSession.updateById(meterManage);
    }

    @Override
    public void importExcelCheck(JSONObject jsonObject) {
       excelTool.excelImport(jsonObject, MeterManageImportDTO.class);
    }


    /**
     * 水电燃气仪表导入
     * @param jsonObject
     * @param token
     * @return
     */
    @Override
    public Object importExcel(JSONObject jsonObject, Token token) throws Exception {
        //初始化excel数据开始的行数，为每个数据添加下标
        Integer[] arr = {3};
        List<MeterManageImportDTO> dtoList = excelTool.excelImport(jsonObject, MeterManageImportDTO.class);
        dtoList = dtoList.stream().peek(d->d.setIndex(arr[0]++)).collect(Collectors.toList());
        //准备返回所需的数据
        int importTotal = dtoList.size();
        StringBuilder errorMsg = new StringBuilder();
        //查询DB判断是否存在重复的仪表编号
        List<String> importMeterNoList = dtoList.stream().map(m ->m.getMeterNo()).collect(Collectors.toList());
        List<String> importRepeatNos = importMeterNoList.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()))
                .entrySet().stream().filter(e -> e.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toList());
        if (!Objects.isEmpty(importRepeatNos)) {
            List<Integer> errorIndex = dtoList.stream().filter(d -> importRepeatNos.contains(d.getMeterNo()))
                    .map(d -> d.getIndex()).collect(Collectors.toList());

            errorMsg.append(String.format("第%s行,[仪表编号]重复\n", errorIndex));
            ImportResult isNull = getImportResult(dtoList, importTotal, errorMsg, errorIndex);
            if (isNull != null) {return isNull;}
        }

        FindArray<MeterManage> arrayFind = jdbcSession.findArray(MeterManage.class);
        arrayFind.eq("deleted",false);
        arrayFind.in("meterNo",importMeterNoList);
        List<MeterManage> dbMeterList = arrayFind.exe();
        if(!Objects.isEmpty(dbMeterList)){
            List<String> dbMeterNos = dbMeterList.stream().map(db -> db.getMeterNo()).collect(Collectors.toList());
            List<Integer> errorIndex = dtoList.stream().filter(d -> dbMeterNos.contains(d.getMeterNo()))
                    .map(d -> d.getIndex()).collect(Collectors.toList());

            errorMsg.append(String.format("第%s行,[仪表编号]系统中已经存在\n", errorIndex));
            ImportResult isNull = getImportResult(dtoList, importTotal, errorMsg, errorIndex);
            if (isNull != null) {return isNull;}
        }
        //仪表类型
        Set<String> importTypeSet = dtoList.stream().map(d -> d.getMeterTypeName()).collect(Collectors.toSet());

        FindArray<MeterTypeConfig> typeFind = jdbcSession.findArray(MeterTypeConfig.class);
        typeFind.eq("deleted",false);
        typeFind.eq("status",true);
        typeFind.in("typeName",importTypeSet);
        List<MeterTypeConfig> dbMeterTypeList = typeFind.exe();
        if(Objects.isEmpty(dbMeterTypeList)){
            errorMsg.append("导入的[仪表类型]系统中均不存在.");
            return excelTool.R(importTotal,0,errorMsg.toString());
        }

        Set<String> dbTypeSet = dbMeterTypeList.stream().map(t ->t.getTypeName()).collect(Collectors.toSet());
        List<Integer> notTypeNames = dtoList.stream().filter(d -> !dbTypeSet.contains(d.getMeterTypeName()))
                .map(d -> d.getIndex()).collect(Collectors.toList());
        if(!Objects.isEmpty(notTypeNames)){
            errorMsg.append(String.format("第%s行,[仪表类型]系统中不存在\n", notTypeNames));
            ImportResult isNull = getImportResult(dtoList, importTotal, errorMsg, notTypeNames);
            if (isNull != null) {return isNull;}
        }
        //仪表分类
        Set<String> importClassSet = dtoList.stream().map(m -> m.getMeterClassifyName()).collect(Collectors.toSet());

        FindArray<MeterClassify> classFind = jdbcSession.findArray(MeterClassify.class);
        classFind.eq("deleted",false);
        classFind.in("typeName",importClassSet);
        List<MeterClassify> dbMeterClassList = classFind.exe();
        if(Objects.isEmpty(dbMeterClassList)){
            errorMsg.append("导入的[仪表分类名称]系统中均不存在.");
            return excelTool.R(importTotal,0,errorMsg.toString());
        }

        List<String> stateCloses = dbMeterClassList.stream().filter(c -> !c.isStatus()).map(c -> c.getTypeName()).collect(Collectors.toList());
        if(!Objects.isEmpty(stateCloses)){

            List<Integer> closeClass = dtoList.stream().filter(d -> stateCloses.contains(d.getMeterClassifyName()))
                    .map(d -> d.getIndex()).collect(Collectors.toList());

            errorMsg.append(String.format("第%s行,[仪表分类名称]状态已经关闭，无法添加仪表\n", closeClass));
            ImportResult isNull = getImportResult(dtoList, importTotal, errorMsg, closeClass);
            if (isNull != null) {return isNull;}
        }

        List<String> dbClassSet = dbMeterClassList.stream().map(c -> c.getTypeName()).collect(Collectors.toList());
        List<Integer> notFindClassList = dtoList.stream().filter(i -> !dbClassSet.contains(i.getMeterClassifyName()))
                .map(d->d.getIndex()).collect(Collectors.toList());
        if(!Objects.isEmpty(notFindClassList)){
            errorMsg.append(String.format("第%s行,[仪表分类]系统中不存在\n", notFindClassList));
            ImportResult isNull = getImportResult(dtoList, importTotal, errorMsg, notFindClassList);
            if (isNull != null) {return isNull;}
        }
        //小区名称、楼栋、单元、房号
        Set<String> importCommunitySet = dtoList.stream().map(d -> d.getCommunityName()).collect(Collectors.toSet());
        Set<String> importBuildSet = dtoList.stream().map(d -> d.getBuildName()).collect(Collectors.toSet());
        /*Set<String> importUnitNameSet = dtoList.stream().map(d -> d.getUnitName()).collect(Collectors.toSet());
        importUnitNameSet.removeAll(Collections.singleton(null));*/
        Set<String> houseNumberSet = dtoList.stream().map(d -> d.getFloorName()+d.getHouseName()).collect(Collectors.toSet());

        JSONObject json = new JSONObject();
        json.put("buildSet",importBuildSet);
        json.put("communitySet",importCommunitySet);
        json.put("houseNumberSet",houseNumberSet);
        //json.put("unitNameSet",importUnitNameSet);
        List<ChargeHouseConfig> dbHouseList = commonClient.getResidentListByMultipleQuery(json);
        if(Objects.isEmpty(dbHouseList)){
            errorMsg.append("导入的[小区名称]、[楼栋]、[楼层]、[房号]均无法匹配到住户信息.");
            return excelTool.R(importTotal,0,errorMsg.toString());
        }

        //同一种类型仪表一个房间仅能有一个
        Set<String> houseSet = dbHouseList.stream().map(h -> h.getHouseNo()).collect(Collectors.toSet());
        FindArray<MeterManage> meterFind = jdbcSession.findArray(MeterManage.class);
        meterFind.eq("deleted",false);
        meterFind.in("houseNo",houseSet);
        List<MeterManage> dbHouseMeterList = meterFind.exe();

        //操作人信息-----------------------------------------------------------------------------------------------
        String departmentName = null;
        List<String> departmentNos = null;
        String username = token.getUsername();
        String departmentNo = null;
        List<String> departList = token.getDepartments();
        if (!Objects.isEmpty(departList)) {
            DeptDTO dept = deptService.getDept(departList.get(0));
            departmentNo = dept.getDepartmentNo();
            departmentName = dept.getDepartmentName();
            departmentNos = dept.getDepartmentNos();
        }
        //orm
        List<MeterManage> unOrmList = new ArrayList<>();
        for(Iterator<MeterManageImportDTO> i = dtoList.iterator(); i.hasNext(); ) {
            MeterManageImportDTO importDTO = i.next();
            List<Integer> index = new ArrayList<>();
            index.add(importDTO.getIndex());

            //格式统一化楼栋和单元
            importDTO.setBuildName(ConvertUtils.formatHouseBuildName(importDTO.getBuildName()));
            importDTO.setUnitName(ConvertUtils.formatHouseUnitName(importDTO.getUnitName()));

            MeterManage meterManage = Pool.newInstance(MeterManage.class);
            Beans.from((JSONObject) JSONObject.toJSON(importDTO)).to(meterManage).igornNull().copy();

            String address = ConvertUtil.jointAddress(importDTO.getCommunityName()
                    , importDTO.getBuildName(), importDTO.getUnitName(), importDTO.getFloorName()+importDTO.getHouseName());
            meterManage.setMeterAddress(address);

            //同一种类型仪表一个房间仅能有一个
            ChargeHouseConfig houseConfig = dbHouseList.stream().filter(h -> h.getCommunityName()
                    .equals(importDTO.getCommunityName()) && h.getBuildName().equals(importDTO.getBuildName())
                    && h.getMergeName().equals(importDTO.getFloorName()+importDTO.getHouseName())).findFirst().orElse(null);
            if(null == houseConfig){
                errorMsg.append(String.format("第%s行,[小区名称]、[楼栋]、[楼层]、[房号]没有匹配到住户信息\n", index));
                i.remove();
                continue;
            }

            long count = dbHouseMeterList.stream().filter(m -> m.getHouseNo()
                    .equals(houseConfig.getHouseNo()) && m.getMeterTypeName().equals(importDTO.getMeterTypeName())).count();
            if(count > 0){
                errorMsg.append(String.format("第%s行,该房屋已经存在相同的[仪表类型],无法再添加\n", index));
                i.remove();
                continue;
            }

            ChargeHouseConfig community = dbHouseList.stream().filter(h -> importDTO.getCommunityName()
                    .equals(h.getCommunityName())).findFirst().orElse(null);
            if(null != community){
                meterManage.setCommunityNo(community.getCommunityNo());
            }

            MeterTypeConfig meterType = dbMeterTypeList.stream().filter(t -> t.getTypeName()
                    .equals(importDTO.getMeterTypeName())).findFirst().orElse(null);
            if(null != meterType){
                meterManage.setMeterTypeNo(meterType.getId());
            }

            MeterClassify classify = dbMeterClassList.stream().filter(c -> c.getTypeName()
                    .equals(importDTO.getMeterClassifyName())).findFirst().orElse(null);
            if(null != classify){
                meterManage.setMeterClassifyNo(classify.getId());
            }
            meterManage.setHouseNo(houseConfig.getHouseNo());
            meterManage.setCreateName(username);
            meterManage.setDepartmentNo(departmentNo);
            meterManage.setDepartmentNos(departmentNos);
            meterManage.setDepartmentName(departmentName);

            unOrmList.add(meterManage);
        }
        int successCount = jdbcSession.insert(unOrmList).length;
        return excelTool.R(importTotal,successCount,errorMsg.toString());
    }

    private ImportResult getImportResult(List<MeterManageImportDTO> dtoList, int importTotal, StringBuilder errorMsg, List<Integer> errorIndex) {
        dtoList.removeIf(d->errorIndex.contains(d.getIndex()));
        if(Objects.isEmpty(dtoList)){
            return excelTool.R(importTotal,0, errorMsg.toString());
        }
        return null;
    }



    @Override
    public Object update(MeterManage meterManage) {
        if (meterManage.isStatus()) {
            List<MeterManage> meterManageList = jdbcSession.findArray(MeterManage.class).eq("communityNo", meterManage.getCommunityNo())
                    .eq("houseNo", meterManage.getHouseNo()).eq("meterTypeNo", meterManage.getMeterTypeNo())
                    .eq("status", true).eq("deleted", false).noEq("id", meterManage.getId()).exe();
            if (Objects.nonEmpty(meterManageList)) {
                logger.info("已有同类型启用");
                return Result.error(3002, "同一仪表类型只能有一个启用状态");
            }
        }

        commonService.insetLogger(meterManage.getMeterNo(),
                ChargeLogEnum.LOG_CHARGE_METER.getDesc(),
                "修改仪表",
                ChargeStatusEnum.CS_SUCCESS.getDesc(),
                ChargeStatusEnum.CS_SUCCESS.getDesc(), "操作成功", meterManage.getUpdateName());

        return jdbcSession.updateById(meterManage);
    }


    @Override
    public Object deleteById(String id) {
        MeterManage result = Pool.get(MeterManage.class, id);
        if (result != null) {
            result.setDeleted(true);
            jdbcSession.updateById(result);
        }
        return 1;
    }


    @Override
    public Page<MeterStatistDTO> findMeterStatist(JSONObject jsonObject) throws Exception {
        PageCondition query = Condition.createPage(false);

        String communityNo = jsonObject.getString("communityNo");
        if(!StringUtil.isEmpty(communityNo)){
            query.eq("communityNo",communityNo);
        }
        String communityName = jsonObject.getString("communityName");
        if(!StringUtil.isEmpty(communityName)){
            query.like("communityName",communityName);
        }
        String meterTypeNo = jsonObject.getString("meterTypeNo");
        if(!StringUtil.isEmpty(meterTypeNo)){
            query.eq("meterTypeNo", meterTypeNo);
        }
        //添加选中导出条件
        JSONArray exportIdList = jsonObject.getJSONArray("exportIdList");
        if(!Objects.isEmpty(exportIdList)){
            query.in("communityNo",exportIdList);
        }

        query.eq("deleted", false);
        query.groupBy("communityNo");
        query.order("createTime","desc");
        query.page(jsonObject);
        Page<HashMap> page = chargeMeterDao.findPage(query);
        return convert(page);
    }

    @Override
    public Object findMeterObj(JSONObject jsonObject) {
        List<MeterManage> meterManageList = jdbcSession.findArray(MeterManage.class)
                .eq("deleted", false)
                .eq(jsonObject, "meterNo")
                .eq(jsonObject, "houseNo")
                .eq(jsonObject, "meterTypeNo")
                .eq(jsonObject, "meterAddress")
                .eq("status", true)
                .order("createTime", "desc")
                .exe();
        if (Objects.nonEmpty(meterManageList)) {
            return Result.success(meterManageList.get(0));
        }
        return Result.success();
    }


    /**
     * 仪表统计excel导出
     *
     * @param req
     * @param resp
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Override
    public void downMeterStatist(HttpServletRequest req, HttpServletResponse resp, JSONObject jsonObject) throws Exception {
        jsonObject.put("pageNo", 1);
        jsonObject.put("pageSize", Short.MAX_VALUE);
        List<MeterStatistDTO> meterStatistAll = findMeterStatist(jsonObject).getList();
        Assert.notEmpty(meterStatistAll,"没有找到相关的仪表数据.");
        excelTool.excelDownload(req,resp,meterStatistAll,"仪表统计导出");
    }

    private Page<MeterStatistDTO> convert(Page<HashMap> page) {
        Page<MeterStatistDTO> result = new Page<>();
        result.setPageSize(page.getPageSize());
        result.setPageNo(page.getPageNo());
        result.setPageCount(page.getPageCount());
        result.setCount(page.getCount());
        result.setOffSet(page.getOffSet());
        List<HashMap> list = page.getList();
        if (Objects.nonEmpty(list)) {
            List<MeterStatistDTO> dataList = new ArrayList<>();
            for (HashMap each : list) {

                MeterStatistDTO item = new MeterStatistDTO();
                item.setMeterGasNumber(Integer.parseInt(each.get("meterGasNumber").toString()));
                item.setMeterWaterNumber(Integer.parseInt(each.get("meterWaterNumber").toString()));
                item.setMeterWattNumber(Integer.parseInt(each.get("meterWattNumber").toString()));
                //item.setMeterTypeName((String) each.get("meterTypeName"));
                //item.setMeterTypeNo((String) each.get("meterTypeNo"));
                item.setCommunityName((String) each.get("communityName"));
                item.setCommunityNo((String) each.get("communityNo"));
                dataList.add(item);
            }
            result.setList(dataList);
        }
        return result;
    }
}
